﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Warburton.FastBitArray.Implementations
{
    internal class DefaultBitArray
        : IBitArray
    {
        private readonly System.Collections.BitArray _bitArray;
        private readonly IBitArrayFactory _factory;

        internal System.Collections.BitArray UnderlyingBitArray { get { return _bitArray; } }

        public IBitArrayFactory Factory
        {
            get { return _factory; }
        }

        internal DefaultBitArray(IBitArrayFactory factory, System.Collections.BitArray bitArray)
        {
            _factory = factory;
            _bitArray = bitArray;
        }

        public int NumberOfBits
        {
            get { return _bitArray.Count; }
        }

        public bool Get(int index)
        {
            return _bitArray.Get(index);
        }

        public IBitArray Set(int index, bool value)
        {
            _bitArray.Set(index, value);
            return this;
        }

        public IBitArray SetAll(bool value)
        {
            _bitArray.SetAll(value);
            return this;
        }

        public IBitArray And(IBitArray value)
        {
            var managed = value as DefaultBitArray;
            if (managed != null)
                _bitArray.And(managed._bitArray);
            else
                throw new ArgumentException("Don't currently support cross BitArray logical operations");
            return this;
        }

        public IBitArray Or(IBitArray value)
        {
            var managed = value as DefaultBitArray;
            if (managed != null)
                _bitArray.Or(managed._bitArray);
            else
                throw new ArgumentException("Don't currently support cross BitArray logical operations");
            return this;
        }

        public IBitArray Xor(IBitArray value)
        {
            var managed = value as DefaultBitArray;
            if (managed != null)
                _bitArray.Xor(managed._bitArray);
            else
                throw new ArgumentException("Don't currently support cross BitArray logical operations");
            return this;
        }

        public IBitArray Not()
        {
            _bitArray.Not();
            return this;
        }

        public IEnumerable<int> GetIndexes(bool value)
        {
            for (int i = 0; i < _bitArray.Length; ++i)
                if (_bitArray.Get(i) == value)
                    yield return i;
        }
    }
}
